/*
	This file is part of the OdinMS Maple Story Server
    Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> 
                       Matthias Butz <matze@odinms.de>
                       Jan Christian Meyer <vimes@odinms.de>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License version 3
    as published by the Free Software Foundation. You may not use, modify
    or distribute this program under any other version of the
    GNU Affero General Public License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package net.sf.odinms.client.messages.commands;

import java.io.BufferedReader;
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import java.io.File;

import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLConnection;  

import net.sf.odinms.client.MapleClient;
import net.sf.odinms.client.messages.Command;
import net.sf.odinms.client.messages.CommandDefinition;
import net.sf.odinms.client.messages.IllegalCommandSyntaxException;
import net.sf.odinms.client.messages.MessageCallback;
import net.sf.odinms.tools.Pair;
import net.sf.odinms.tools.StringUtil;

import net.sf.odinms.provider.MapleData;
import net.sf.odinms.provider.MapleDataProvider;
import net.sf.odinms.provider.MapleDataTool;
import net.sf.odinms.provider.MapleDataProviderFactory;


public class SearchCommands implements Command {

	@Override 
    public void execute(MapleClient c, MessageCallback mc, String[] splitted) throws Exception, IllegalCommandSyntaxException { 
        if (splitted.length > 0) { 
            if (splitted[0].equalsIgnoreCase("!search") || splitted[0].equalsIgnoreCase("!s")) { 
                if (splitted.length > 2) { 
                String type = splitted[1];
                String search = StringUtil.joinStringFrom(splitted, 2);


                List<String> retSearch = new ArrayList<String>();
                MapleDataProvider dataProvider = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/String.wz"));
                List<Pair<Integer, String>> searchPairList = new LinkedList<Pair<Integer, String>>();
                MapleData data;

                if (type.equalsIgnoreCase("SKILL") || type.equalsIgnoreCase("SKILLS")) {
                    data = dataProvider.getData("Skill.img");
                    for (MapleData searchIdData : data.getChildren()) {
                        int searchIdFromData = Integer.parseInt(searchIdData.getName());
                        String searchNameFromData = MapleDataTool.getString(searchIdData.getChildByPath("name"), "NO-NAME");
                        if (retSearch.size() < 30) {
                            if (searchNameFromData.toLowerCase().contains(search.toLowerCase())) {
                                retSearch.add("SKILL[" + searchIdFromData + "] " + searchNameFromData);
                            }
                        } else {
                            break;
                        }
                    }
                } else if (type.equalsIgnoreCase("USE") || type.equalsIgnoreCase("CONSUME")) {
                    data = dataProvider.getData("Consume.img");
                    for (MapleData searchIdData : data.getChildren()) {
                        int searchIdFromData = Integer.parseInt(searchIdData.getName());
                        String searchNameFromData = MapleDataTool.getString(searchIdData.getChildByPath("name"), "NO-NAME");
                        if (retSearch.size() < 30) {
                            if (searchNameFromData.toLowerCase().contains(search.toLowerCase())) {
                                retSearch.add("USE[" + searchIdFromData + "] " + searchNameFromData);
                            }
                        } else {
                            break;
                        }
                    }
                } else if (type.equalsIgnoreCase("CASH")) {
                    data = dataProvider.getData("Cash.img");
                    for (MapleData searchIdData : data.getChildren()) {
                        int searchIdFromData = Integer.parseInt(searchIdData.getName());
                        String searchNameFromData = MapleDataTool.getString(searchIdData.getChildByPath("name"), "NO-NAME");
                        if (retSearch.size() < 30) {
                            if (searchNameFromData.toLowerCase().contains(search.toLowerCase())) {
                                retSearch.add("CASH[" + searchIdFromData + "] " + searchNameFromData);
                            }
                        } else {
                            break;
                        }
                    }
                } else if (type.equalsIgnoreCase("MONSTER") || type.equalsIgnoreCase("MOB")) {
                    data = dataProvider.getData("Mob.img");
                    for (MapleData searchIdData : data.getChildren()) {
                        int searchIdFromData = Integer.parseInt(searchIdData.getName());
                        String searchNameFromData = MapleDataTool.getString(searchIdData.getChildByPath("name"), "NO-NAME");
                        if (retSearch.size() < 30) {
                            if (searchNameFromData.toLowerCase().contains(search.toLowerCase())) {
                                retSearch.add("MONSTER[" + searchIdFromData + "] " + searchNameFromData);
                            }
                        } else {
                            break;
                        }
                    }
                } else if (type.equalsIgnoreCase("NPC")) {
                    data = dataProvider.getData("Npc.img");
                    for (MapleData searchIdData : data.getChildren()) {
                        int searchIdFromData = Integer.parseInt(searchIdData.getName());
                        String searchNameFromData = MapleDataTool.getString(searchIdData.getChildByPath("name"), "NO-NAME");
                        searchPairList.add(new Pair<Integer, String>(searchIdFromData, searchNameFromData));
                        if (retSearch.size() < 30) {
                            if (searchNameFromData.toLowerCase().contains(search.toLowerCase())) {
                                retSearch.add("NPC[" + searchIdFromData + "] " + searchNameFromData);
                            }
                        } else {
                            break;
                        }
                    }
                } else if (type.equalsIgnoreCase("EQUIP")) {
                    data = dataProvider.getData("Eqp.img");
                    for (MapleData eqpData : data.getChildren()) {
                        for (MapleData equipSections : eqpData.getChildren()) {
                            String equipSectionName = equipSections.getName();
                            for (MapleData searchIdData : equipSections.getChildren()) {
                                int searchIdFromData = Integer.parseInt(searchIdData.getName());
                                String searchNameFromData = equipSectionName + ": " + MapleDataTool.getString(searchIdData.getChildByPath("name"), "NO-NAME");
                                if (retSearch.size() < 30) {
                                    if (searchNameFromData.toLowerCase().contains(search.toLowerCase())) {
                                        retSearch.add("EQUIP[" + searchIdFromData + "] " + searchNameFromData);
                                    }
                                } else {
                                    break;
                                }
                            }
                        }
                    }
                } else if (type.equalsIgnoreCase("ETC")) {
                    data = dataProvider.getData("Etc.img");
                    MapleData data2 = data.getChildByPath("Etc");
                    for (MapleData searchIdData : data2.getChildren()) {
                        int searchIdFromData = Integer.parseInt(searchIdData.getName());
                        String searchNameFromData = MapleDataTool.getString(searchIdData.getChildByPath("name"), "NO-NAME");
                        if (retSearch.size() < 30) {
                            if (searchNameFromData.toLowerCase().contains(search.toLowerCase())) {
                                retSearch.add("ETC[" + searchIdFromData + "] " + searchNameFromData);
                            }
                        } else {
                            break;
                        }
                    }
                } else if (type.equalsIgnoreCase("MAP")) {
                    data = dataProvider.getData("Map.img");
                    for (MapleData continentData : data.getChildren()) {
                        String continentNameFromData = continentData.getName();
                        for (MapleData searchIdData : continentData.getChildren()) {
                            int searchIdFromData = Integer.parseInt(searchIdData.getName());
                            String searchNameFromData = MapleDataTool.getString(searchIdData.getChildByPath("mapName"), "NO-NAME");
                            if (retSearch.size() < 30) {
                                if (searchNameFromData.toLowerCase().contains(search.toLowerCase())) {
                                    retSearch.add("MAP[" + searchIdFromData + "] " + continentNameFromData + ": " + searchNameFromData);
                                }
                            } else {
                                break;
                            }
                        }
                    }
                } else {
                    mc.dropMessage("ERROR: '" + type + "' is not a valid search type.  Valid options are MAP, USE, ETC, CASH, EQUIP, MOB (or MONSTER), or SKILL.");
                    return;
                }

                if (data != null) {
                    mc.dropMessage("Search for '" + search + "' was completed.");
                    if (retSearch != null && retSearch.size() > 0) {
                                for (String singleRet : retSearch) {
                                    mc.dropMessage(singleRet);
                        }
                    } else {
                        mc.dropMessage("No " + type + " fit your search criteria");
                    }
                    if (retSearch != null && retSearch.size() > 29) {
                        mc.dropMessage("More than 30 results returned, please refine your search.");
                    }

                    data = null;
                    retSearch = null;
                }
            } else {
                mc.dropMessage("Invalid search.  Proper usage: '!search <type> <search for>', where <type> is MAP, USE, ETC, CASH, EQUIP, MOB (or MONSTER), or SKILL.");
            }
        } else if (splitted[0].equals("!mesos")){
            c.getPlayer().gainMeso(Integer.parseInt(splitted[1]), true);
        } else if (splitted[0].equalsIgnoreCase("!msearch") || splitted[0].equalsIgnoreCase("!ms")){
            mc.dropMessage("msearch chosen");
            try {
                URL                url;
                URLConnection      urlConn;
                BufferedReader     dis;

                String replaced = "";

                if (splitted.length > 1) {
                    replaced = StringUtil.joinStringFrom(splitted, 1).replace(' ', '%');
                } else {
                    mc.dropMessage("Syntax: !search item name/map name/monster name");
                }

                url = new URL("http://www.mapletip.com/search_java.php?search_value=" + replaced + "&check=true");


                urlConn = url.openConnection();
                urlConn.setDoInput(true);
                urlConn.setUseCaches(false);

                dis = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                String s;

                while ((s = dis.readLine()) != null) {
                    mc.dropMessage(s);
                }

                mc.dropMessage("Search for " + '"' + replaced.replace('%', ' ') + '"' + " was completed.");
                dis.close();
            }
            catch (MalformedURLException mue) {
                mc.dropMessage("Malformed URL Exception: " + mue.toString());
            }
            catch (IOException ioe) {
                mc.dropMessage("IO Exception: " + ioe.toString());
            }
            catch (Exception e) {
                mc.dropMessage("General Exception: " + e.toString());
            }
        }
    }
} 

    @Override 
    public CommandDefinition[] getDefinition() { 
        return new CommandDefinition[] {
            new CommandDefinition("find", "", "", 100),
            new CommandDefinition("mesos", "", "", 100),
            new CommandDefinition("lookup", "", "", 100),
            new CommandDefinition("search", "", "", 1),
            new CommandDefinition("msearch", "", "", 1),
            new CommandDefinition("s", "", "", 1),
            new CommandDefinition("ms", "", "", 1),
        };
    }  
}